#!/bin/bash
# Clear All Database Data Script
# WARNING: This script will permanently delete ALL data from the database

echo "🗑️ Database Clear Script - DANGER ZONE"

# Color definitions
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m'

SERVER_URL="http://47.108.201.156"

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

log_danger() {
    echo -e "${RED}[DANGER]${NC} $1"
}

log_success() {
    echo -e "${PURPLE}[SUCCESS]${NC} $1"
}

# Check dependencies
check_dependencies() {
    log_step "Checking dependencies..."
    
    if ! command -v curl >/dev/null 2>&1; then
        log_error "curl command not available"
        exit 1
    fi
    
    if ! command -v jq >/dev/null 2>&1; then
        log_warn "jq command not available, using basic processing"
        JQ_AVAILABLE=false
    else
        JQ_AVAILABLE=true
    fi
    
    log_info "✅ Dependencies check completed"
}

# Check server status
check_server() {
    log_step "Checking server status..."
    
    response=$(curl -s -w "%{http_code}" -o /dev/null "$SERVER_URL/admin/users")
    
    if [ "$response" == "200" ]; then
        log_info "✅ Server is running normally"
    else
        log_error "❌ Server is not accessible, HTTP status: $response"
        exit 1
    fi
}

# Show warning and get confirmation
show_warning_and_confirm() {
    echo ""
    echo "========================================"
    log_danger "⚠️  EXTREME WARNING  ⚠️"
    echo "========================================"
    echo ""
    log_danger "This script will PERMANENTLY DELETE ALL DATA from the database!"
    echo ""
    echo "📋 Data that will be DELETED:"
    echo "  ❌ ALL user accounts (admins, teachers, students, viewers)"
    echo "  ❌ ALL classes and class schedules"
    echo "  ❌ ALL courses and course assignments"
    echo "  ❌ ALL teacher teaching assignments"
    echo "  ❌ ALL activity logs and audit trails"
    echo "  ❌ ALL weekly schedule records"
    echo ""
    log_danger "THIS OPERATION CANNOT BE UNDONE!"
    echo ""
    echo "🔄 After clearing, the database will be completely empty."
    echo "🔄 You will need to run the demo data generator to restore functionality."
    echo ""
    
    # Triple confirmation
    echo "========================================"
    log_danger "CONFIRMATION REQUIRED"
    echo "========================================"
    
    read -p "Are you absolutely sure you want to delete ALL data? (type 'YES' to confirm): " confirm1
    if [ "$confirm1" != "YES" ]; then
        log_info "Operation cancelled by user"
        exit 0
    fi
    
    read -p "This will delete EVERYTHING in the database. Type 'DELETE ALL' to proceed: " confirm2
    if [ "$confirm2" != "DELETE ALL" ]; then
        log_info "Operation cancelled by user"
        exit 0
    fi
    
    read -p "Last chance! Type 'I UNDERSTAND' to proceed with complete data deletion: " confirm3
    if [ "$confirm3" != "I UNDERSTAND" ]; then
        log_info "Operation cancelled by user"
        exit 0
    fi
    
    echo ""
    log_danger "🚨 PROCEEDING WITH COMPLETE DATA DELETION 🚨"
    echo ""
}

# Get current data statistics before deletion
get_pre_deletion_stats() {
    log_step "Getting current data statistics..."
    
    # Get user count
    users_response=$(curl -s "$SERVER_URL/admin/users")
    if [ "$JQ_AVAILABLE" = true ]; then
        user_count=$(echo "$users_response" | jq -r '.users | length' 2>/dev/null || echo "unknown")
    else
        user_count="unknown"
    fi
    
    # Get class count
    classes_response=$(curl -s "$SERVER_URL/admin/classes")
    if [ "$JQ_AVAILABLE" = true ]; then
        class_count=$(echo "$classes_response" | jq -r '.classes | length' 2>/dev/null || echo "unknown")
    else
        class_count="unknown"
    fi
    
    # Get schedule count
    schedules_response=$(curl -s "$SERVER_URL/admin/schedules")
    if [ "$JQ_AVAILABLE" = true ]; then
        schedule_count=$(echo "$schedules_response" | jq -r '.schedules | length' 2>/dev/null || echo "unknown")
    else
        schedule_count="unknown"
    fi
    
    # Get log count
    logs_response=$(curl -s "$SERVER_URL/admin/logs")
    if [ "$JQ_AVAILABLE" = true ]; then
        log_count=$(echo "$logs_response" | jq -r '.logs | length' 2>/dev/null || echo "unknown")
    else
        log_count="unknown"
    fi
    
    log_info "📊 Current database statistics:"
    log_info "  Users: $user_count"
    log_info "  Classes: $class_count"
    log_info "  Schedule records: $schedule_count"
    log_info "  Activity logs: $log_count"
}

# Clear all users
clear_all_users() {
    log_step "Clearing all users..."
    
    users_response=$(curl -s "$SERVER_URL/admin/users")
    
    if [ "$JQ_AVAILABLE" = true ]; then
        # Extract all user IDs and delete them one by one
        echo "$users_response" | jq -r '.users[]?.userID // empty' | while read user_id; do
            if [ -n "$user_id" ]; then
                log_info "Deleting user: $user_id"
                response=$(curl -s -X DELETE "$SERVER_URL/admin/users/$user_id")
                if echo "$response" | grep -q "successfully"; then
                    log_info "✅ Deleted user: $user_id"
                else
                    log_warn "⚠️ Failed to delete user: $user_id - $response"
                fi
                sleep 0.1  # Small delay to avoid overwhelming the server
            fi
        done
    else
        log_warn "Cannot delete users individually without jq. Manual cleanup may be required."
    fi
    
    log_info "✅ User deletion process completed"
}

# Clear all classes (this will cascade delete schedules)
clear_all_classes() {
    log_step "Clearing all classes..."
    
    classes_response=$(curl -s "$SERVER_URL/admin/classes")
    
    if [ "$JQ_AVAILABLE" = true ]; then
        # Extract all class IDs and delete them one by one
        echo "$classes_response" | jq -r '.classes[]?.ID // empty' | while read class_id; do
            if [ -n "$class_id" ]; then
                # Get class name for logging
                class_name=$(echo "$classes_response" | jq -r ".classes[] | select(.ID==$class_id) | .name" 2>/dev/null || echo "Unknown")
                log_info "Deleting class: $class_name (ID: $class_id)"
                
                response=$(curl -s -X DELETE "$SERVER_URL/admin/classes/$class_id")
                if echo "$response" | grep -q "successfully"; then
                    # Extract deletion statistics
                    deleted_schedules=$(echo "$response" | jq -r '.deletedSchedules // 0' 2>/dev/null || echo "unknown")
                    deleted_teacher_slots=$(echo "$response" | jq -r '.deletedTeacherSlots // 0' 2>/dev/null || echo "unknown")
                    
                    log_info "✅ Deleted class: $class_name"
                    log_info "  - Schedules deleted: $deleted_schedules"
                    log_info "  - Teacher slots deleted: $deleted_teacher_slots"
                else
                    log_warn "⚠️ Failed to delete class: $class_name - $response"
                fi
                sleep 0.2  # Slightly longer delay for class deletion
            fi
        done
    else
        log_warn "Cannot delete classes individually without jq. Manual cleanup may be required."
    fi
    
    log_info "✅ Class deletion process completed"
}

# Clear all teacher plans
clear_all_teacher_plans() {
    log_step "Clearing remaining teacher plans..."
    
    # Clear plans for known teacher IDs
    teacher_ids=("2000000001" "2000000002" "2000000003" "2000000004" "2000000005")
    
    for teacher_id in "${teacher_ids[@]}"; do
        log_info "Clearing plans for teacher: $teacher_id"
        response=$(curl -s -X DELETE "$SERVER_URL/api/teacher/teach-schedule/all?teacherId=$teacher_id")
        
        if echo "$response" | grep -q "cleared"; then
            log_info "✅ Cleared plans for teacher: $teacher_id"
        else
            log_warn "⚠️ Failed to clear plans for teacher: $teacher_id - $response"
        fi
        sleep 0.1
    done
    
    log_info "✅ Teacher plan clearing completed"
}

# Verify database is empty
verify_database_empty() {
    log_step "Verifying database is empty..."
    
    # Check users
    users_response=$(curl -s "$SERVER_URL/admin/users")
    if [ "$JQ_AVAILABLE" = true ]; then
        remaining_users=$(echo "$users_response" | jq -r '.users | length' 2>/dev/null || echo "unknown")
    else
        remaining_users="unknown"
    fi
    
    # Check classes
    classes_response=$(curl -s "$SERVER_URL/admin/classes")
    if [ "$JQ_AVAILABLE" = true ]; then
        remaining_classes=$(echo "$classes_response" | jq -r '.classes | length' 2>/dev/null || echo "unknown")
    else
        remaining_classes="unknown"
    fi
    
    # Check schedules
    schedules_response=$(curl -s "$SERVER_URL/admin/schedules")
    if [ "$JQ_AVAILABLE" = true ]; then
        remaining_schedules=$(echo "$schedules_response" | jq -r '.schedules | length' 2>/dev/null || echo "unknown")
    else
        remaining_schedules="unknown"
    fi
    
    # Check logs
    logs_response=$(curl -s "$SERVER_URL/admin/logs")
    if [ "$JQ_AVAILABLE" = true ]; then
        remaining_logs=$(echo "$logs_response" | jq -r '.logs | length' 2>/dev/null || echo "unknown")
    else
        remaining_logs="unknown"
    fi
    
    echo ""
    log_info "📊 Post-deletion database statistics:"
    log_info "  Remaining users: $remaining_users"
    log_info "  Remaining classes: $remaining_classes"
    log_info "  Remaining schedules: $remaining_schedules"
    log_info "  Remaining logs: $remaining_logs"
    
    # Check if database appears empty
    if [ "$remaining_users" == "0" ] && [ "$remaining_classes" == "0" ] && [ "$remaining_schedules" == "0" ]; then
        log_success "✅ Database appears to be completely cleared!"
    elif [ "$remaining_users" == "unknown" ]; then
        log_warn "⚠️ Unable to verify database state (jq not available)"
    else
        log_warn "⚠️ Some data may still remain in the database"
        if [ "$remaining_users" != "0" ]; then
            log_warn "  - $remaining_users users still exist"
        fi
        if [ "$remaining_classes" != "0" ]; then
            log_warn "  - $remaining_classes classes still exist"
        fi
        if [ "$remaining_schedules" != "0" ]; then
            log_warn "  - $remaining_schedules schedule records still exist"
        fi
    fi
}

# Show next steps
show_next_steps() {
    echo ""
    echo "========================================"
    log_success "🎉 DATABASE CLEARING COMPLETED"
    echo "========================================"
    echo ""
    log_info "📋 Next Steps:"
    echo "  1. The database is now completely empty"
    echo "  2. The web application will not function until data is restored"
    echo "  3. To restore demo data, run:"
    echo "     ./generate-test-data.sh"
    echo ""
    echo "  4. To restore from backup, run:"
    echo "     ./restore-database.sh"
    echo ""
    log_warn "⚠️ Remember: The cleared data cannot be recovered unless you have backups!"
    echo ""
    echo "🌐 Server URL: $SERVER_URL:3000"
    echo "========================================"
}

# Main execution flow
main() {
    echo "========================================"
    echo "🗑️ DATABASE COMPLETE CLEARING TOOL"
    echo "📅 Started: $(date)"
    echo "🌐 Target Server: $SERVER_URL"
    echo "========================================"
    
    check_dependencies
    check_server
    show_warning_and_confirm
    get_pre_deletion_stats
    clear_all_users
    clear_all_classes
    clear_all_teacher_plans
    verify_database_empty
    show_next_steps
}

# Quick clear without confirmation (DANGEROUS!)
quick_clear() {
    log_danger "🚨 PERFORMING QUICK CLEAR WITHOUT CONFIRMATION 🚨"
    
    check_dependencies
    check_server
    get_pre_deletion_stats
    clear_all_users
    clear_all_classes
    clear_all_teacher_plans
    verify_database_empty
    
    log_success "✅ Quick clear completed!"
}

# Script parameter handling
case "${1:-}" in
    "quick")
        log_danger "⚠️ WARNING: Quick clear mode - NO CONFIRMATION REQUIRED"
        read -p "Are you sure you want to proceed with quick clear? (y/N): " quick_confirm
        if [[ "$quick_confirm" =~ ^[Yy]$ ]]; then
            quick_clear
        else
            log_info "Quick clear cancelled"
            exit 0
        fi
        ;;
    "help"|"-h"|"--help")
        echo "Database Complete Clearing Tool"
        echo ""
        echo "⚠️ WARNING: This tool permanently deletes ALL database data!"
        echo ""
        echo "Usage:"
        echo "  $0          - Interactive clear with triple confirmation"
        echo "  $0 quick    - Quick clear with minimal confirmation (DANGEROUS!)"
        echo "  $0 help     - Show this help message"
        echo ""
        echo "What gets deleted:"
        echo "  - All user accounts (admins, teachers, students, viewers)"
        echo "  - All classes and schedules"
        echo "  - All courses and assignments"
        echo "  - All teacher teaching plans"
        echo "  - All activity logs"
        echo ""
        echo "Recovery options:"
        echo "  - Run ./generate-test-data.sh to restore demo data"
        echo "  - Run ./restore-database.sh to restore from backup"
        echo ""
        echo "⚠️ CAUTION: Deleted data cannot be recovered without backups!"
        ;;
    *)
        main
        ;;
esac


